<!--
 * @Author: lisong
 * @Date: 2023-04-17 16:22:20
 * @LastEditors: lisong
 * @LastEditTime: 2023-04-24 16:38:38
 * @Description: 投资计划表格
-->
<template>
  <rk-grid
      ref="rkGridRef"
      title=""
      boxConfig
      :data="data"
      :columns="columns"
      :loading="loading"
      :editConfig="true"
      :keepSource="true"
      :pagerConfig="false"
  >
    <template #toolbar_title_buttons>
      <el-button type="primary" plain @click="handleOperation('add','新增行')">新增行</el-button>
      <el-button type="danger" plain @click="handleOperation('delete','删除行')">删除行</el-button>
    </template>
    <template #rk_select_year_edit="{row,column}">
      <el-date-picker v-model="row[column.field]" value-format="YYYY" type="year" placeholder="选择年">
      </el-date-picker>
    </template>
    <template #rk_input_sspa_edit="{row,column}">
      <vxe-input v-model="row[column.field]" type="text"
                 @change="blurEvent(row,column)"
                 @focus="focusEvent(row,column)"
                 clearable
                 align="right"
      ></vxe-input>
    </template>
    <template #rk_input_bpa_edit="{row,column}">
      <vxe-input v-model="row[column.field]" type="text" @blur="blurEvent(row,column)"
                 @focus="focusEvent(row,column)" clearable align="right"></vxe-input>
    </template>
    <template #rk_input_fpa_edit="{row,column}">
      <vxe-input v-model="row[column.field]" type="text" @blur="blurEvent(row,column)"
                 @focus="focusEvent(row,column)" align="right" clearable></vxe-input>
    </template>
    <template #rk_input_mpa_edit="{row,column}">
      <vxe-input v-model="row[column.field]" type="text" @blur="blurEvent(row,column)"
                 @focus="focusEvent(row,column)" align="right" clearable></vxe-input>
    </template>
    <template #rk_input_opa_edit="{row,column}">
      <vxe-input v-model="row[column.field]" type="text" @blur="blurEvent(row,column)"
                 @focus="focusEvent(row,column)" align="right" clearable></vxe-input>
    </template>
  </rk-grid>
</template>

<script setup name="ProjectTzjhTable">

import {getCurrentInstance, onBeforeMount, onMounted, reactive} from "vue";
import {queryInvestPlanByProId} from "../../../api/api-project";

// 向上触发的方法
const emits = defineEmits([
  'setFormItemValue'
])
const loading = ref(false)

const props = defineProps({
  // 组件的名称，用于组织插槽数据，提供给表单设计器以及渲染器（必须定义）
  title: {type: String, default: '投资计划表格'},
  // 表单数据信息
  formData: {type: Object, default: () => {
    return {
      proId: 'test'
    }
  }}
})
const {appContext} = getCurrentInstance();
const globalProxy = appContext.config.globalProperties;
// 表格的模板引用
const rkGridRef = ref()

// ----- 表格相关操作
const defaultColumns = [
  {
    field: 'SET_YEAR',
    title: '年度',
    width: 120,
    align: 'left',
    editRender: {autofocus: '.el-input__inner'},
    slots: {edit: 'rk_select_year_edit'}
  },
  {
    field: 'YEAR_SUM_AMT',
    title: '年度总投资',
    width: 150,
    align: 'right',
    className: 'gs-cell-bg',
  },
  {
    field: 'SUP_SUBS_PLAN_AMT',
    title: '上级补助资金-计划投资',
    width: 235,
    align: 'right',

    editRender: {autofocus: '.el-input__inner'},
    slots: {edit: 'rk_input_sspa_edit'}
  },
  {
    field: 'BUDG_PLAN_AMT',
    title: '本级财政预算资金-计划投资',
    width: 235,
    align: 'right',
    editRender: {autofocus: '.el-input__inner'},
    slots: {edit: 'rk_input_bpa_edit'}
  },
  {
    field: 'FINA_PLAN_AMT',
    title: '融资资金-计划投资',
    width: 235,
    align: 'right',
    editRender: {autofocus: '.el-input__inner'},
    slots: {edit: 'rk_input_fpa_edit'}
  },
  {
    field: 'MARK_PLAN_AMT',
    title: '市场化融资资金-计划投资',
    width: 235,
    align: 'right',
    editRender: {autofocus: '.el-input__inner'},
    slots: {edit: 'rk_input_mpa_edit'}
  },
  {
    field: 'OTHER_PLAN_AMT',
    title: '其他资金-计划投资',
    width: 235,
    align: 'right',
    editRender: {autofocus: '.el-input__inner'},
    slots: {edit: 'rk_input_opa_edit'}
  },
]
const defaultData = {
  PLAN_ID: '',
  SET_YEAR: '',
  YEAR_SUM_AMT: 0,
  SUP_SUBS_PLAN_AMT: 0,
  BUDG_PLAN_AMT: 0,
  FINA_PLAN_AMT: 0,
  MARK_PLAN_AMT: 0,
  SELF_PLAN_AMT: 0,
  OTHER_PLAN_AMT: 0,
}
const initTzjhData = [{
  PLAN_ID: '',
  SET_YEAR: '',
  YEAR_SUM_AMT: 0,
  SUP_SUBS_PLAN_AMT: 0,
  BUDG_PLAN_AMT: 0,
  FINA_PLAN_AMT: 0,
  MARK_PLAN_AMT: 0,
  SELF_PLAN_AMT: 0,
  OTHER_PLAN_AMT: 0,
}]
const queryParam = reactive({
  map: void 0,
  proId: ""
})

const data = ref(initTzjhData)
const columns = ref(defaultColumns)


// ----- emits 方法定义
/**
 * 向上触发的方法，修改表单中的字段信息
 *
 * @param {String} fieldName 字段名称
 * @param {String} fieldValue 字段值
 */
const emitSetFormItemValue = function (fieldName, fieldValue) {
  emits('setFormItemValue', fieldName, fieldValue)
}

// ----- 获取组件数据
/**
 * 获取投资计划数据的方法，暴露给表单调用，固定名称getCompData
 */
const getCompData = function () {
  const {fullData} = rkGridRef.value.getTableData()
  return {
    'pro_plan_grid': JSON.parse(JSON.stringify(fullData))
  }
}

//处理新增行删除行
const handleOperation = async (buttonType, textName) => {
  if (buttonType === 'add') {
    const {row: newRow} = await rkGridRef.value.insertAt(defaultData)
    await rkGridRef.value.setEditCell(newRow, 'name')
  } else if (buttonType === 'delete') {
    const selectRows = rkGridRef.value.getCheckboxRecords()
    if (selectRows.length === 0 || !selectRows) {
      globalProxy.$message({message: `请勾选要删除的数据！`, type: "warning"});
      return;
    }
    rkGridRef.value.removeCheckboxRow()
  }
}

//失去焦点事件
const blurEvent = async (row, column) => {
  row.YEAR_SUM_AMT = Number(row.SUP_SUBS_PLAN_AMT) + Number(row.BUDG_PLAN_AMT) + Number(row.FINA_PLAN_AMT) + Number(row.MARK_PLAN_AMT) + Number(row.SELF_PLAN_AMT) + Number(row.OTHER_PLAN_AMT)
  if (rkGridRef.value.reloadRow) {
    await rkGridRef.value.reloadRow(row)
  }
  calculateTotalBudget()
}

//计算项目总概算
const calculateTotalBudget = () => {
  const {tableData} = rkGridRef.value.getTableData()
  let totalBudget = 0
  if (tableData) {
    tableData.forEach(item => {
      totalBudget += Number(item['YEAR_SUM_AMT'])
    })
  }
  emitSetFormItemValue('TOTAL_BUDGET', totalBudget)
  emitSetFormItemValue('PRO_TOTAL_AMT', totalBudget)
}

//得到焦点事件
const focusEvent = (row, column) => {
  if (!row['SET_YEAR']) {
    globalProxy.$message({message: `请填写投资计划列表中"年度"列！`, type: "warning"});
  }
}
//请求初始化数据
onMounted(async () => {
  loading.value = true
  const {proId} = props.formData
  if (proId) {
    queryParam.proId = proId
    const res = await queryInvestPlanByProId(queryParam)
    if (res.code === 200) {
      data.value = res.data
    }
  }
  loading.value = false
})


defineExpose({
  getCompData
})

</script>

<style lang="scss" scoped>
:deep(.gs-cell-bg) {
  background-color: #e6e6e6;
}
</style>
